<?php

namespace api\utils;

use SplFileObject;
use Yii;

class ExportUtil
{
    public static function exportCsv($filename, $header, $rows): SplFileObject
    {
        $file = self::createFile($filename);
        $file->fwrite(chr(0xEF) . chr(0xBB) . chr(0xBF));
        $file->fputcsv(array_values($header));
        foreach ($rows as $row) {
            $file->fputcsv($row);
        }
        return $file;
    }

    public static function createFile(?string $filename): SplFileObject
    {
        $date = date('Y-m-d');
        $runtime = Yii::$app->getRuntimePath();

        $filename = "exportfile" . DIRECTORY_SEPARATOR . "$date" . DIRECTORY_SEPARATOR . trim($filename, DIRECTORY_SEPARATOR);
        $file_path_info = pathinfo($filename);

        $file_path = '';
        foreach (explode(DIRECTORY_SEPARATOR , $file_path_info['dirname']) as $dir_item) {
            $file_path = trim("$file_path" . DIRECTORY_SEPARATOR . "$dir_item", DIRECTORY_SEPARATOR);
            !is_dir("$runtime".DIRECTORY_SEPARATOR ."$file_path") && mkdir("$runtime/$file_path");
        }
        return new SplFileObject("$runtime" .DIRECTORY_SEPARATOR."$file_path" .DIRECTORY_SEPARATOR . $file_path_info['basename'], 'x+');
    }

}
